<template>
  <div class="member-center">
    <!-- 会员中心头部 -->
    <div class="member-header">
      <h1>会员中心</h1>
      <div class="member-stats" v-if="currentUser">
        <div class="stat-item">
          <span class="stat-label">会员状态</span>
          <span :class="['stat-value', currentUser.isMember ? 'active' : 'inactive']">
            {{ currentUser.isMember ? '已开通' : '未开通' }}
          </span>
        </div>
        <div class="stat-item" v-if="currentUser.isMember">
          <span class="stat-label">会员等级</span>
          <span :class="['stat-value', `level-${currentUser.memberLevel}`]">
            {{ getMemberLevelName(currentUser.memberLevel) }}
          </span>
        </div>
        <div class="stat-item" v-if="currentUser.isMember && currentUser.memberExpires">
          <span class="stat-label">有效期至</span>
          <span class="stat-value">
            {{ formatDate(currentUser.memberExpires) }}
            <span class="days-remaining">
              ({{ getRemainingDays(currentUser.memberExpires) }}天)
            </span>
          </span>
        </div>
      </div>
    </div>

    <!-- 会员权益展示 -->
    <div class="member-benefits">
      <h2>会员权益</h2>
      <div class="benefits-grid">
        <div class="benefit-card">
          <div class="benefit-icon">🎬</div>
          <div class="benefit-title">无广告观看</div>
          <div class="benefit-desc">享受纯净观影体验</div>
        </div>
        <div class="benefit-card">
          <div class="benefit-icon">📺</div>
          <div class="benefit-title">高清画质</div>
          <div class="benefit-desc">最高支持4K超清</div>
        </div>
        <div class="benefit-card">
          <div class="benefit-icon">⬇️</div>
          <div class="benefit-title">高速下载</div>
          <div class="benefit-desc">离线观看更便捷</div>
        </div>
        <div class="benefit-card">
          <div class="benefit-icon">🔒</div>
          <div class="benefit-title">专属内容</div>
          <div class="benefit-desc">会员专享独家视频</div>
        </div>
      </div>
    </div>

    <!-- 会员套餐选择 -->
    <div class="member-plans">
      <h2>{{ currentUser?.isMember ? '续费/升级会员' : '开通会员' }}</h2>
      <div class="plans-grid">
        <div 
          v-for="(plan, index) in memberPlans" 
          :key="index"
          :class="['plan-card', { selected: selectedPlan === plan.level }]"
          @click="selectedPlan = plan.level"
        >
          <div class="plan-header">
            <h3>{{ plan.name }}</h3>
            <div class="plan-price">¥{{ plan.price }}/月</div>
          </div>
          <div class="plan-features">
            <div v-for="(feature, idx) in plan.features" :key="idx" class="feature-item">
              ✅ {{ feature }}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 购买时长选择 -->
      <div class="duration-selector">
        <label>选择时长：</label>
        <div class="duration-options">
          <button 
            v-for="duration in durationOptions" 
            :key="duration.months"
            :class="['duration-btn', { active: selectedDuration === duration.months }]"
            @click="selectedDuration = duration.months"
          >
            {{ duration.label }} (¥{{ duration.totalPrice(selectedPlan) }})
          </button>
        </div>
      </div>
      
      <!-- 购买按钮 -->
      <button 
        class="purchase-btn"
        @click="purchaseMember"
        :disabled="processing"
      >
        {{ processing ? '处理中...' : `${currentUser?.isMember ? '立即续费' : '立即开通'}` }}
      </button>
    </div>

    <!-- 会员使用数据 -->
    <div class="member-stats-section" v-if="currentUser?.isMember">
      <h2>使用数据</h2>
      <div class="stats-grid">
        <div class="data-card">
          <div class="data-label">本月观看时长</div>
          <div class="data-value">{{ userStats.watchTime }} 分钟</div>
        </div>
        <div class="data-card">
          <div class="data-label">收藏视频数</div>
          <div class="data-value">{{ userStats.favorites }} 个</div>
        </div>
        <div class="data-card">
          <div class="data-label">下载视频数</div>
          <div class="data-value">{{ userStats.downloads }} 个</div>
        </div>
      </div>
    </div>

    <!-- 会员历史记录 -->
    <div class="member-history" v-if="memberHistory.length > 0">
      <h2>会员记录</h2>
      <div class="history-list">
        <div v-for="(record, index) in memberHistory" :key="index" class="history-item">
          <div class="history-date">{{ formatDate(record.date) }}</div>
          <div class="history-action">{{ record.action }}</div>
          <div class="history-details">{{ record.details }}</div>
        </div>
      </div>
    </div>

    <!-- 推荐内容 -->
    <div class="recommended-content">
      <h2>会员推荐</h2>
      <div class="content-grid">
        <div v-for="(item, index) in recommendedItems" :key="index" class="content-card">
          <div class="content-poster">
            <div class="poster-placeholder">{{ item.icon }}</div>
          </div>
          <div class="content-info">
            <div class="content-title">{{ item.title }}</div>
            <div class="content-desc">{{ item.description }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 通知消息 -->
    <div class="member-notices">
      <h2>会员通知</h2>
      <div class="notice-list">
        <div v-for="(notice, index) in memberNotices" :key="index" class="notice-item">
          <div class="notice-icon">📢</div>
          <div class="notice-content">
            <div class="notice-title">{{ notice.title }}</div>
            <div class="notice-text">{{ notice.content }}</div>
            <div class="notice-time">{{ notice.time }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮组 -->
    <div class="action-buttons" v-if="currentUser?.isMember">
      <button class="action-btn cancel" @click="showCancelConfirm = true">
        取消自动续费
      </button>
      <button class="action-btn gift" @click="showGiftConfirm = true">
        赠送好友
      </button>
    </div>

    <!-- 确认对话框 -->
    <div class="modal" v-if="showCancelConfirm || showGiftConfirm">
      <div class="modal-content">
        <h3>{{ showCancelConfirm ? '取消自动续费' : '赠送会员' }}</h3>
        <p v-if="showCancelConfirm">
          确定要取消自动续费吗？取消后，当前会员权益将持续到到期日。
        </p>
        <p v-else>
          请输入好友用户名进行会员赠送。
        </p>
        <input 
          v-if="showGiftConfirm" 
          v-model="giftUsername" 
          type="text" 
          placeholder="好友用户名"
          class="gift-input"
        >
        <div class="modal-buttons">
          <button class="modal-btn cancel" @click="closeModal">
            取消
          </button>
          <button 
            class="modal-btn confirm" 
            @click="showCancelConfirm ? doCancelMember() : doGiftMember()"
          >
            确认
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getCurrentUser, activateMember, cancelMember, getMemberHistory, giftMember } from '@/utils/auth'

const currentUser = ref(null)
const selectedPlan = ref('standard')
const selectedDuration = ref(1)
const processing = ref(false)
const showCancelConfirm = ref(false)
const showGiftConfirm = ref(false)
const giftUsername = ref('')

// 会员套餐定义
const memberPlans = [
  {
    level: 'standard',
    name: '标准会员',
    price: 19,
    features: ['无广告观看', '高清画质', '基础下载']
  },
  {
    level: 'premium', 
    name: '高级会员',
    price: 39,
    features: ['无广告观看', '超高清画质', '高速下载', '专属内容', '多设备登录']
  }
]

// 时长选项
const durationOptions = [
  { months: 1, label: '1个月' },
  { months: 3, label: '3个月', discount: 0.9 },
  { months: 6, label: '6个月', discount: 0.8 },
  { months: 12, label: '12个月', discount: 0.7 }
]

// 用户统计数据
const userStats = ref({
  watchTime: 125,
  favorites: 8,
  downloads: 5
})

// 会员历史记录
const memberHistory = ref([])

// 推荐内容
const recommendedItems = [
  {
    icon: '🌟',
    title: '会员专属纪录片',
    description: '深入幕后的制作故事'
  },
  {
    icon: '🔥',
    title: '新上线独家剧集',
    description: '提前观看最新内容'
  },
  {
    icon: '💎',
    title: '导演剪辑版',
    description: '从未公开的精彩片段'
  }
]

// 会员通知
const memberNotices = [
  {
    title: '系统维护通知',
    content: '尊敬的会员，系统将于本周六凌晨2-4点进行维护，期间可能出现短暂服务中断。',
    time: '2024-02-20 10:00'
  },
  {
    title: '新功能上线',
    content: '会员专属收藏夹功能已上线，您可以创建多个收藏分类了！',
    time: '2024-02-18 14:30'
  }
]

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取会员等级名称
const getMemberLevelName = computed(() => {
  return (level) => {
    const plan = memberPlans.find(p => p.level === level)
    return plan ? plan.name : '普通用户'
  }
})

// 计算剩余天数
const getRemainingDays = computed(() => {
  return (expires) => {
    if (!expires) return 0
    const now = new Date()
    const exp = new Date(expires)
    const diff = Math.ceil((exp - now) / (1000 * 60 * 60 * 24))
    return Math.max(0, diff)
  }
})

// 计算套餐总价
const calculateTotalPrice = computed(() => {
  return (level, months) => {
    const plan = memberPlans.find(p => p.level === level)
    if (!plan) return 0
    
    const duration = durationOptions.find(d => d.months === months)
    const discount = duration?.discount || 1
    
    return Math.round(plan.price * months * discount)
  }
})

// 扩展durationOptions，添加totalPrice方法
for (const duration of durationOptions) {
  duration.totalPrice = function(level) {
    return calculateTotalPrice(level, this.months)
  }
}

// 购买会员
function purchaseMember() {
  if (!currentUser.value) return
  
  processing.value = true
  
  try {
    // 调用会员开通/续费方法
    const result = activateMember(currentUser.value.username, selectedDuration.value, selectedPlan.value)
    
    // 更新用户信息
    updateUser()
    
    // 由于activateMember已自动添加历史记录，这里无需手动添加
    alert('操作成功！')
  } catch (error) {
    alert('操作失败：' + error.message)
  } finally {
    processing.value = false
  }
}

// 取消会员
function doCancelMember() {
  if (!currentUser.value) return
  
  try {
    const result = cancelMember(currentUser.value.username)
    updateUser()
    
    memberHistory.value.unshift({
      date: new Date().toISOString(),
      action: '取消会员',
      details: '已取消会员服务'
    })
    
    alert('已取消会员！')
  } catch (error) {
    alert('操作失败：' + error.message)
  } finally {
    closeModal()
  }
}

// 赠送会员
function doGiftMember() {
  if (!giftUsername.value.trim()) {
    alert('请输入好友用户名')
    return
  }
  
  processing.value = true
  
  try {
    // 调用赠送会员API
    const result = giftMember(currentUser.value.username, giftUsername.value, 1, selectedPlan.value)
    
    // 更新会员历史记录
    loadMemberHistory()
    
    alert(`已成功赠送给 ${giftUsername.value} 一个月的${getMemberLevelName(selectedPlan.value)}！`)
  } catch (error) {
    alert('赠送失败：' + error.message)
  } finally {
    processing.value = false
    closeModal()
  }
}

// 关闭弹窗
function closeModal() {
  showCancelConfirm.value = false
  showGiftConfirm.value = false
  giftUsername.value = ''
}

// 更新用户信息
function updateUser() {
  currentUser.value = getCurrentUser()
  console.log('用户信息:', currentUser.value)
  
  // 如果用户已登录，加载会员历史记录
  if (currentUser.value) {
    loadMemberHistory()
  }
}

// 加载会员历史记录
function loadMemberHistory() {
  if (!currentUser.value) return
  
  try {
    memberHistory.value = getMemberHistory(currentUser.value.username)
    console.log('会员历史记录:', memberHistory.value)
  } catch (error) {
    console.error('加载会员历史记录失败:', error)
  }
}

onMounted(() => {
  updateUser()
  
  // 监听认证状态变化
  window.addEventListener('auth-changed', updateUser)
})
</script>

<style scoped>
.member-center {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 头部样式 */
.member-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 30px;
}

.member-header h1 {
  margin: 0 0 20px 0;
  font-size: 32px;
}

.member-stats {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
}

.stat-value.active {
  color: #4ade80;
}

.stat-value.inactive {
  color: #fbbf24;
}

.stat-value.level-standard {
  color: #60a5fa;
}

.stat-value.level-premium {
  color: #c084fc;
}

.days-remaining {
  font-size: 14px;
  font-weight: normal;
  opacity: 0.8;
}

/* 通用区块样式 */
.member-center h2 {
  color: #333;
  margin: 40px 0 20px 0;
  font-size: 24px;
  border-left: 4px solid #667eea;
  padding-left: 12px;
}

/* 权益展示 */
.benefits-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.benefit-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: transform 0.2s, box-shadow 0.2s;
}

.benefit-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.benefit-icon {
  font-size: 40px;
  margin-bottom: 15px;
}

.benefit-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.benefit-desc {
  color: #666;
  font-size: 14px;
}

/* 套餐选择 */
.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 25px;
}

.plan-card {
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 25px;
  cursor: pointer;
  transition: all 0.3s;
}

.plan-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
}

.plan-card.selected {
  border-color: #667eea;
  background: linear-gradient(135deg, #f5f7ff 0%, #ffffff 100%);
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e5e7eb;
}

.plan-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.plan-price {
  font-size: 22px;
  font-weight: bold;
  color: #667eea;
}

.plan-features {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.feature-item {
  font-size: 14px;
  color: #555;
}

/* 时长选择 */
.duration-selector {
  margin-bottom: 25px;
}

.duration-selector label {
  display: block;
  margin-bottom: 10px;
  font-weight: bold;
  color: #333;
}

.duration-options {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.duration-btn {
  padding: 10px 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

.duration-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.duration-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

/* 购买按钮 */
.purchase-btn {
  display: block;
  width: 100%;
  max-width: 300px;
  margin: 0 auto;
  padding: 15px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.3s;
}

.purchase-btn:hover:not(:disabled) {
  background: #5a67d8;
}

.purchase-btn:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

/* 统计数据 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.data-card {
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.data-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #667eea;
}

/* 历史记录 */
.history-list {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.history-item {
  display: grid;
  grid-template-columns: 120px 1fr 1fr;
  gap: 20px;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.history-date {
  font-size: 14px;
  color: #666;
}

.history-action {
  font-weight: bold;
  color: #333;
}

.history-details {
  color: #666;
  font-size: 14px;
}

/* 推荐内容 */
.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.content-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.content-card:hover {
  transform: translateY(-5px);
}

.poster-placeholder {
  height: 180px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 60px;
  color: white;
}

.content-info {
  padding: 15px;
}

.content-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.content-desc {
  font-size: 14px;
  color: #666;
}

/* 通知 */
.notice-list {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.notice-item {
  display: flex;
  gap: 15px;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-icon {
  font-size: 30px;
  flex-shrink: 0;
}

.notice-content {
  flex: 1;
}

.notice-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
  color: #333;
}

.notice-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.5;
}

.notice-time {
  font-size: 12px;
  color: #999;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 20px;
  margin-top: 40px;
  justify-content: center;
}

.action-btn {
  padding: 12px 30px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.action-btn.cancel {
  background: #fef2f2;
  color: #ef4444;
  border: 1px solid #fecaca;
}

.action-btn.cancel:hover {
  background: #fee2e2;
}

.action-btn.gift {
  background: #ecfdf5;
  color: #10b981;
  border: 1px solid #a7f3d0;
}

.action-btn.gift:hover {
  background: #d1fae5;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 30px;
  max-width: 500px;
  width: 90%;
}

.modal-content h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.modal-content p {
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
}

.gift-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 16px;
}

.modal-buttons {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.modal-btn {
  padding: 10px 25px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.modal-btn.cancel {
  background: #f3f4f6;
  color: #6b7280;
}

.modal-btn.cancel:hover {
  background: #e5e7eb;
}

.modal-btn.confirm {
  background: #667eea;
  color: white;
}

.modal-btn.confirm:hover {
  background: #5a67d8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .member-center {
    padding: 15px;
  }
  
  .member-header {
    padding: 20px;
  }
  
  .member-stats {
    flex-direction: column;
    gap: 15px;
  }
  
  .history-item {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>